package com.leetcodehot.problems;

import java.util.*;

public class problems2583 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public long kthLargestLevelSum(TreeNode root, int k) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        List<Long> res = new ArrayList<>();
        deque.addFirst(root);
        while (!deque.isEmpty()) {
            int n = deque.size();
            long sum = 0;
            while (n-- > 0) {
                TreeNode node = deque.removeFirst();
                sum += node.val;
                if (node.left != null) deque.addLast(node.left);
                if (node.right != null) deque.addLast(node.right);
            }
            res.add(sum);
        }
        if (k > res.size()) return -1L;
        Collections.sort(res);
        return res.get(res.size() - k);
    }
}
